package fran.pinggoogle.network;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;

import fran.pinggoogle.PingGooglePrincipal;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;

public class PingMaker {
	private PingGooglePrincipal mAct;
	private boolean bandera;
	PipedOutputStream mPOut;
	PipedInputStream mPIn;
	LineNumberReader mReader;
	Process mProcess;

	/*
	 * 
	 */
	public void pingGoogle(PingGooglePrincipal act) {
		mAct = act;
		bandera = true;
		new pingGoogle().execute();
	}

	public class pingGoogle extends AsyncTask<Void, String, Void> {

		private boolean resultado;

		/*
		 * 
		 */
		public pingGoogle() {

		}

		@Override
		protected void onPreExecute() {
			mPOut = new PipedOutputStream();
			try {
				mPIn = new PipedInputStream(mPOut);
				mReader = new LineNumberReader(new InputStreamReader(mPIn));
			} catch (IOException e) {
				cancel(true);
			}

		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				while (bandera) {
					// String pingGoogle = Network.ping();
					// String[] values = new String[]{pingGoogle};
					// publishProgress(values);
					// Thread.sleep(500);
					mProcess = new ProcessBuilder()
							.command(new String[]{"su","-c","ping -c 1 www.google.com"})
							.redirectErrorStream(true).start();
					mProcess.waitFor();
					InputStream in = mProcess.getInputStream();
					OutputStream out = mProcess.getOutputStream();
					byte[] buffer = new byte[1024];
					int count;

					// in -> buffer -> mPOut -> mReader -> 1 line of ping
					// information to parse
					while ((count = in.read(buffer)) != -1) {
						mPOut.write(buffer, 0, count);
						publishProgress();
					}
					out.close();
					in.close();
					mProcess.destroy();
					mProcess = null;
					Thread.sleep(500);
				}
			} catch (Exception ex) {
				Log.d("PINGMAKER", ex.getMessage());
			}finally{
				try {
					mPOut.close();
					mPIn.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

		}

		@Override
		protected void onProgressUpdate(String... values) {
			try {
				StringBuffer result = new StringBuffer("");
				while (mReader.ready()) {
					result.append(mReader.readLine()+"\n");
				}
				mAct.addPingResult(result);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void setBandera(boolean bandera) {
		this.bandera = bandera;
	}
}
